package me.thinkjet.sso.client.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpUtils {

	public static String constructRedirectUrl(final String serverLoginUrl,
			final String serviceName, final String serviceUrl) {
		try {
			return serverLoginUrl
					+ (serverLoginUrl.indexOf("?") != -1 ? "&" : "?")
					+ serviceName + "="
					+ URLEncoder.encode(serviceUrl, "UTF-8");
		} catch (final UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String constructServiceUrl(final HttpServletRequest request,
			final HttpServletResponse response, final String ticketName,
			final boolean encode) {
		final StringBuilder buffer = new StringBuilder();

		buffer.append(request.getRequestURL());

		if (CommonUtils.isNotBlank(request.getQueryString())) {
			final int location = request.getQueryString().indexOf(
					ticketName + "=");

			if (location == 0) {
				final String returnValue = encode ? response.encodeURL(buffer
						.toString()) : buffer.toString();
				return returnValue;
			}

			buffer.append("?");

			if (location == -1) {
				buffer.append(request.getQueryString());
			} else if (location > 0) {
				final int actualLocation = request.getQueryString().indexOf(
						"&" + ticketName + "=");

				if (actualLocation == -1) {
					buffer.append(request.getQueryString());
				} else if (actualLocation > 0) {
					buffer.append(request.getQueryString().substring(0,
							actualLocation));
				}
			}
		}

		final String returnValue = encode ? response.encodeURL(buffer
				.toString()) : buffer.toString();
		return returnValue;
	}

	public static String safeGetParameter(final HttpServletRequest request,
			final String parameter) {
		if ("POST".equals(request.getMethod())
				&& "logoutRequest".equals(parameter)) {
			return request.getParameter(parameter);
		}
		return request.getQueryString() == null
				|| request.getQueryString().indexOf(parameter) == -1 ? null
				: request.getParameter(parameter);
	}

	public static String getResponseFromServer(final URL constructedUrl,
			final String encoding) {
		URLConnection conn = null;
		try {
			conn = constructedUrl.openConnection();
			final BufferedReader in;

			if (CommonUtils.isEmpty(encoding)) {
				in = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
			} else {
				in = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), encoding));
			}

			String line;
			final StringBuilder stringBuffer = new StringBuilder(255);

			while ((line = in.readLine()) != null) {
				stringBuffer.append(line);
				stringBuffer.append("\n");
			}
			return stringBuffer.toString();
		} catch (final Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null && conn instanceof HttpURLConnection) {
				((HttpURLConnection) conn).disconnect();
			}
		}

	}

	public static String getResponseFromServer(final String url, String encoding) {
		try {
			return getResponseFromServer(new URL(url), encoding);
		} catch (final MalformedURLException e) {
			throw new IllegalArgumentException(e);
		}
	}

	public static void sendRedirect(final HttpServletResponse response,
			final String url) {
		try {
			response.sendRedirect(url);
		} catch (final Exception e) {
		}

	}
}
